package avicit.bdp.dcs.json.service.builder;

import avicit.bdp.common.utils.CheckParaUtils;
import avicit.bdp.dcs.job.dto.JobDTO;
import avicit.bdp.dcs.job.service.DcsJobService;
import avicit.bdp.dcs.json.service.reader.ApiReaderBuilder;
import avicit.bdp.dcs.json.service.util.BuildJsonUtil;
import avicit.bdp.dcs.json.service.writer.ApiWriterBuilder;
import avicit.bdp.dcs.plugin.BaseDataxParam;
import avicit.bdp.dcs.plugin.TransformerParam;
import avicit.bdp.dcs.task.dto.TaskDTO;
import avicit.bdp.dcs.task.service.TaskService;
import avicit.bdp.dcs.utils.DcsErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class ApiJsonBuilder {

  private static final Logger logger = LoggerFactory.getLogger(ApiJsonBuilder.class);

  @Autowired private TaskService taskService;
  @Autowired private DcsJobService jobService;
  @Autowired private BuildJsonUtil buildJsonUtil;
  @Autowired private ApiWriterBuilder apiWriterBuilder;
  @Autowired private ApiReaderBuilder apiReaderBuilder;

  /**
   * 结构化采集
   *
   * @param taskId 任务ID
   * @return datax json
   * @throws Exception build json exception
   */
  public String buildDataxJsonByAPI(String taskId) throws Exception {
    // 1、参数合法性校验
    TaskDTO taskDTO = taskService.selectByPrimaryKey(taskId);
    CheckParaUtils.checkDbObjectValidity(
        taskDTO, logger, String.format(DcsErrorCode.TASK_NULL.getDesc(), taskId));
    JobDTO jobDTO = jobService.selectByPrimaryKey(taskDTO.getJobId());
    CheckParaUtils.checkDbObjectValidity(
        jobDTO, logger, String.format(DcsErrorCode.JOB_NULL.getDesc(), taskDTO.getJobId()));

    // 2、构建Reader
    BaseDataxParam readerParam = apiReaderBuilder.buildReaderByAPI(taskDTO, jobDTO);

    // 3、构建Writer
    BaseDataxParam writerParam = apiWriterBuilder.buildWriterByAPI(taskDTO, jobDTO);

    // 4、构建Transformer
    List<TransformerParam> transformerParamList = buildJsonUtil.buildTransformer(taskDTO);

    return buildJsonUtil.buildJobJson(
        jobDTO.getSrcDatasourceId(),
        jobDTO.getDstDatasourceId(),
        readerParam,
        writerParam,
        transformerParamList,
        jobDTO,
        taskDTO);
  }
}
